package com.fjrz.bbxwj.main.mine

import android.os.Bundle
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.LogUtils
import com.module.lemlin.custom.SpacingItemDecoration
import com.fjrz.bbxwj.R
import com.fjrz.bbxwj.entity.UserIsFollow
import com.fjrz.bbxwj.entity.VideoIsLike
import com.fjrz.bbxwj.entity.VideoList
import com.fjrz.bbxwj.main.mine.adapter.UserVideoAdapter
import com.fjrz.bbxwj.main.video.CustomGSYVideoPlayer
import com.fjrz.bbxwj.mode.vm.UserViewModel
import com.module.lemlin.mode.ViewModeFragment
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.msg
import com.module.lemlin.view.LoginAuthPopup
import kotlinx.android.synthetic.main.fragment_user_video.*
import kotlinx.android.synthetic.main.fragment_user_video.mSmartRefreshLayout
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class UserVideoFragment : ViewModeFragment<UserViewModel>() {


    companion object {
        private const val EXTRA_NAME_ACTION = "EXTRA_NAME_ACTION"
        private const val EXTRA_NAME_USER_ID = "EXTRA_NAME_USER_ID"
        private const val VIDEO_WORKS = 0
        private const val VIDEO_LIKES = 1
        fun newInstance(action: Int, userId: Int): UserVideoFragment {
            val bundle: Bundle = Bundle().apply {
                putInt(EXTRA_NAME_ACTION, action)
                putInt(EXTRA_NAME_USER_ID, userId)
            }
            return UserVideoFragment().apply { arguments = bundle }
        }

        val VIDEO_LIST: MutableList<VideoList> = mutableListOf()
    }

    private val videoAdapter = UserVideoAdapter()

    private val mUserId: Int
        get() = arguments?.getInt(EXTRA_NAME_USER_ID) ?: 0

    private val mAction: Int
        get() = arguments?.getInt(EXTRA_NAME_ACTION) ?: 0

    override fun viewModel(): UserViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.fragment_user_video

    override fun initView() {
        rvMineVideoBody.apply {
            val decoration = SpacingItemDecoration(
                nSpan = 2,
                vGap = ConvertUtils.dp2px((10f)),
                hGap = ConvertUtils.dp2px((10f))
            )
            addItemDecoration(decoration)
        }.adapter = videoAdapter.apply {
            setEmptyView(createViewEmptyLoad())
        }

        videoAdapter.setOnItemClickListener { _, _, position ->
            VIDEO_LIST.clear()
            VIDEO_LIST.addAll(videoAdapter.data)
            UserVideoActivity.open(requireActivity(), mUserId,position)
        }

        mSmartRefreshLayout.setEnableRefresh(false)
        //加载更多刷新监听
        mSmartRefreshLayout.setOnLoadMoreListener {
            if (mAction == VIDEO_WORKS) {
                viewModel.userVideos(mUserId, isLoadMore = true)
            } else if (mAction == VIDEO_LIKES) {
                viewModel.userLikeVideos(mUserId, isLoadMore = true)
            }
        }
    }

//    override fun initData() {
//    }

    override fun onResume() {
        super.onResume()
        if (mAction == VIDEO_WORKS) {
            viewModel.userVideos(mUserId)
        } else if (mAction == VIDEO_LIKES) {
            viewModel.userLikeVideos(mUserId)
        }
    }

    override fun initViewMode() {
        viewModel.videoWorksLiveData.observe(viewLifecycleOwner, Observer { response ->
            val status: Status = responseStatus1LiveData(response.status, response.throwable)
            if (status != Status.SUCCESS)
                return@Observer
            val isLoadMore: Boolean = response.httpData?.loadMore ?: false
            val videoLists: MutableList<VideoList> =
                response.httpData?.data?.data ?: mutableListOf()
            setAdapterData(isLoadMore, videoLists)
        })

        viewModel.videoLikesLiveData.observe(viewLifecycleOwner, Observer { response ->
            val status: Status = responseStatus1LiveData(response.status, response.throwable)
            if (status != Status.SUCCESS)
                return@Observer
            val isLoadMore: Boolean = response.httpData?.loadMore ?: false
            val videoLists: MutableList<VideoList> =
                response.httpData?.data?.list ?: mutableListOf()
            setAdapterData(isLoadMore, videoLists)
        })
    }

    private fun setAdapterData(isLoadMore: Boolean, videoLists: MutableList<VideoList>) {
        if (videoLists.isNullOrEmpty()) {
            videoAdapter.setEmptyView(createViewEmptyNull(hint = "暂无数据"))
        }
        if (isLoadMore) {
            videoAdapter.addData(videoLists)
        } else {
            videoAdapter.setNewInstance(videoLists)
        }
        if (videoLists.size < viewModel.limit) {
            videoAdapter.setFooterView(createViewFooter(hint = ""))
            mSmartRefreshLayout.setEnableLoadMore(false)
        } else {
            videoAdapter.removeAllFooterView()
            mSmartRefreshLayout.setEnableLoadMore(true)
        }


    }


    private fun responseStatus1LiveData(status: Status, throwable: Throwable?): Status {
        if (status == Status.START) {
            videoAdapter.setEmptyView(createViewEmptyLoad())
        } else if (status == Status.FAILURE) {
            mSmartRefreshLayout.setEnableLoadMore(false)
            videoAdapter.setEmptyView(createViewEmptyNull(hint = throwable?.msg ?: "未知错误"))
        }
        return status
    }

//    override fun onEventMainThread(any: Any) {
//        if (any is VideoIsLike && mAction == VIDEO_LIKES) {
//            //viewModel.userLikeVideos(mUserId)
//        }
//    }


    override fun onEventMainThread(any: Any) {
        if (any !is LoginAuthPopup.Action)
            return
        if (any == LoginAuthPopup.Action.ACTION_LOGIN_SUCCESS) {
            if (mAction == VIDEO_WORKS) {
                viewModel.userVideos(mUserId)
            } else if (mAction == VIDEO_LIKES) {
                viewModel.userLikeVideos(mUserId)
            }
        }
    }

}